<template>
  <div class="table-editor-container">
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>脚本数据编辑器</span>
        </div>
      </template>

      <el-row :gutter="20" class="search-row">
        <el-col :span="2">
          <el-select v-model="searchType" placeholder="请选择搜索类型" style="width: 100%;">
            <el-option label="包含" :value="SEARCH_TYPES.CONTRAIN"></el-option>
            <el-option label="(顺序)包含" :value="SEARCH_TYPES.SEQ_CONTRAIN"></el-option>
            <el-option label="按照脚本id" :value="SEARCH_TYPES.MATCH_ID"></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="selectedScriptType" placeholder="脚本类型" style="width: 100%;" clearable>
            <el-option v-for="type in scriptTypes" :key="type.value" :label="type.label" :value="type.value"></el-option>
          </el-select>
        </el-col>
        <el-col :span="14">
          <el-input v-model="searchQuery" placeholder="请输入搜索内容" @keyup.enter="handleSearch"></el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" size="default" @click="handleSearch" :loading="isSearching">搜索</el-button>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="search-row">
        <el-col :span="3">
          <el-button type="primary" @click="showAddDialog" style="width: 100%;">
            新建脚本
          </el-button>
        </el-col>
        <el-col :span="3">
          <el-button type="warning" @click="queryPlaceholder" style="width: 100%;" :loading="isSearching">
            占位查询
          </el-button>
        </el-col>
        <el-col :span="3">
          <el-button type="success" @click="showPlaceholderDialog" style="width: 100%;" :loading="isSubmitting">
            脚本占位
          </el-button>
        </el-col>
        <el-col :span="12">
          <div v-if="totalHits !== null" style="margin-top: 10px;">
            搜索结果： {{ lastQueryIndex }} / {{ lastQueryResult.length }}
          </div>
        </el-col>
      </el-row>

      <div class="table-container" v-loading="isSearching">
        <hot-table
          ref="hotTableComponent"
          :settings="hotSettings"
        ></hot-table>
      </div>

      <!-- 新建脚本对话框 -->
      <el-dialog v-model="dialogVisible" title="新建脚本" width="50%" :close-on-click-modal="false">
        <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="120px">
          <el-form-item label="脚本ID" prop="id">
            <el-input-number v-model="addForm.id" :min="1" />
          </el-form-item>
          <el-form-item label="脚本类型" prop="type_str">
            <el-select v-model="addForm.type_str" placeholder="请选择脚本类型" style="width: 100%;">
              <el-option v-for="type in scriptTypes" :key="type.value" :label="type.label" :value="type.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="描述" prop="desc">
            <el-input v-model="addForm.desc" type="textarea" />
          </el-form-item>
          <el-form-item label="备注" prop="note">
            <el-input v-model="addForm.note" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitAdd" :loading="isSubmitting">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 脚本占位对话框 -->
      <el-dialog v-model="placeholderDialogVisible" title="添加脚本占位" width="50%" :close-on-click-modal="false">
        <el-form ref="placeholderFormRef" :model="placeholderForm" :rules="placeholderFormRules" label-width="120px">
          <el-form-item label="脚本类型" prop="type_str">
            <el-select v-model="placeholderForm.type_str" placeholder="请选择脚本类型" style="width: 100%;">
              <el-option v-for="type in scriptTypes" :key="type.value" :label="type.label" :value="type.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="占位个数" prop="count">
            <el-input-number v-model="placeholderForm.count" :min="1" :max="100" />
          </el-form-item>
          <el-form-item label="占位文本" prop="text">
            <el-input v-model="placeholderForm.text" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="placeholderDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitPlaceholder" :loading="isSubmitting">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 编辑脚本对话框 -->
      <el-dialog v-model="editDialogVisible" title="编辑脚本" width="50%" :close-on-click-modal="false">
        <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="120px">
          <el-form-item label="脚本ID" prop="id">
            <el-input-number v-model="editForm.id" :min="1" />
          </el-form-item>
          <el-form-item label="脚本类型" prop="type_str">
            <el-select v-model="editForm.type_str" placeholder="请选择脚本类型" style="width: 100%;">
              <el-option v-for="type in scriptTypes" :key="type.value" :label="type.label" :value="type.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="描述" prop="desc">
            <el-input v-model="editForm.desc" type="textarea" />
          </el-form-item>
          <el-form-item label="备注" prop="note">
            <el-input v-model="editForm.note" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitEdit" :loading="isSubmitting">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, watch, onUnmounted, onBeforeMount } from 'vue'
import { HotTable } from '@handsontable/vue3'
import { registerAllModules } from 'handsontable/registry'
import { registerLanguageDictionary, zhCN } from 'handsontable/i18n'
import type Handsontable from 'handsontable'
import 'handsontable/dist/handsontable.full.min.css'
import { ElMessage} from 'element-plus'
import {
  SEARCH_TYPES,
  type CombatScriptDocument,
  scriptTypeOptions,
  SCRIPT_TYPES,
  type ESSearchResponse,
  SCRIPT_CONSTANTS
} from '../CombatScriptRepDO'
import {
  buildESQuery,
  esSearchScripts,
  SearchAllCombatScript,
  esAddScript,
  esGetMaxId,
  esEditScript
} from '../CombatScriptRep'

import type { FormInstance, FormRules } from 'element-plus'

// 注册所有Handsontable模块
registerAllModules()
// 注册中文语言包
registerLanguageDictionary(zhCN)

// 缓存相关变量
const LOCAL_CACHE_KEY = "TableEditorCacheKey"
const searchCache = ref<{
  key: string;
  results: CombatScriptDocument[];
  totalHits: number;
  timestamp: number;
} | null>(null)
const isFirstLoad = ref(true)

// 搜索相关状态
const searchType = ref(SEARCH_TYPES.CONTRAIN)
const selectedScriptType = ref('')
const searchQuery = ref('')
const isSearching = ref(false)
const scriptTypes = scriptTypeOptions

// 表格数据
const tableData = ref<CombatScriptDocument[]>([])

interface HotTableMethods {
  hotInstance: Handsontable
}

// 组件引用
const hotTableComponent = ref<HotTableMethods | null>(null)

// 表格高度
const tableHeight = ref(500)

// 计算表格高度
const calculateTableHeight = () => {
  
  // 计算总的偏移量
  const totalOffset = 280
  
  // 设置表格高度
  tableHeight.value = window.innerHeight - totalOffset
}

// 表格配置
const hotSettings = ref({
  // 表格数据
  data: tableData,  // 直接使用 tableData 作为数据源
  // 列标题
  colHeaders: ['ID', '类型', '描述', '备注'],
  // 列定义配置
  columns: [
    { 
      data: 'id',                    // 数据字段名
      type: 'numeric',               // 数据类型：数字
      readOnly: true,                // 只读，不可编辑
      width: 10,                     // 列宽（像素）
      className: 'htCenter'          // 居中对齐
    },
    { 
      data: 'type_str',              // 数据字段名
      type: 'text',                  // 数据类型：文本
      // readOnly: true,                // 只读，不可编辑
      width: 15,                     // 列宽（像素）
      className: 'htCenter'          // 居中对齐
    },
    { 
      data: 'desc',                  // 数据字段名
      type: 'text',                  // 数据类型：文本
      // readOnly: true,                // 只读，不可编辑
      width: '60%'                   // 列宽（百分比）
    },
    { 
      data: 'note',                  // 数据字段名
      type: 'text',                  // 数据类型：文本
      // readOnly: true,                // 只读，不可编辑
      width: '20%'                   // 列宽（百分比）
    }
  ],
  minSpareRows: 0,                   // 最小备用行数，0表示不自动添加空行
  width: '100%',                     // 表格宽度，100%表示填充容器
  height: tableHeight,               // 表格高度（动态计算）
  stretchH: 'all',                   // 列宽拉伸模式：all表示所有列自动拉伸
  fixedColumnsStart: 2,              // 左侧固定列数：固定前2列
  contextMenu: {
    items: {
      'edit': {
        name: '编辑',
        callback: (key: any, selection: any[], clickEvent: MouseEvent) => {
          const row = selection[0].start.row;
          const instance = hotTableComponent.value?.hotInstance;
          if (!instance) return;
          
          const rowData = instance.getSourceDataAtRow(row);
          if (rowData && typeof rowData === 'object' && 'id' in rowData && 'type_str' in rowData) {
            showEditDialog(rowData as CombatScriptDocument);
          }
        }
      }
    }
  },
  filters: true,                     // 启用列筛选功能
  dropdownMenu: true,                // 启用下拉菜单
  language: 'zh-CN',                 // 界面语言：中文
  rowHeaders: true,                  // 显示行号
  manualColumnResize: true,          // 允许手动调整列宽
  manualRowResize: true,             // 允许手动调整行高
  columnSorting: true,               // 启用列排序功能
  wordWrap: false,                   // 禁用自动换行
  autoColumnSize: false,             // 禁用自动列宽
  undo: true,                        // 启用撤销/重做功能
  undoRedoMaxLimit: 20,              // 撤销/重做最大步数
  outsideClickDeselects: false,      // 点击表格外部不取消选择
  enterBeginsEditing: false,         // 按Enter键不开始编辑
  enterMoves: { row: 1, col: 0 },    // Enter键移动到下一行
  tabMoves: { row: 0, col: 1 },      // Tab键移动到下一列
  licenseKey: 'non-commercial-and-evaluation'  // Handsontable许可证密钥
})

// 监听数据变化并更新表格
watch(tableData, (newData) => {
  if (hotTableComponent.value?.hotInstance) {
    hotTableComponent.value.hotInstance.loadData(newData)
  }
}, { deep: true })

// 监听窗口大小变化
const handleResize = () => {
  calculateTableHeight()
  if (hotTableComponent.value?.hotInstance) {
    hotTableComponent.value.hotInstance.updateSettings({ height: tableHeight.value })
  }
}

// Add search result tracking variables
const lastQueryContent = ref('')
const lastQueryType = ref(SEARCH_TYPES.CONTRAIN)
const lastQueryScriptType = ref('')
const lastQueryResult = ref<CombatScriptDocument[]>([])
const lastQueryIndex = ref(0)
const totalHits = ref<number | null>(null)

// Add function to update last query
const updateLastQuery = (queryContent: any, queryType: any, queryScriptType: any, queryResult: Array<CombatScriptDocument>) => {
  lastQueryContent.value = queryContent
  lastQueryType.value = queryType
  lastQueryScriptType.value = queryScriptType
  lastQueryResult.value = queryResult
  lastQueryIndex.value = 0
  totalHits.value = queryResult.length
}

// Add function to check if same query
const isSameQuery = (queryContent: any, queryType: any, queryScriptType: any) => {
  return lastQueryResult.value.length > 0 && lastQueryContent.value === queryContent && lastQueryType.value === queryType && lastQueryScriptType.value === queryScriptType
}

// Add function to scroll to row
const scrollToRow = (targetRow: any) => {
  if (!hotTableComponent.value?.hotInstance) return
  
  const instance = hotTableComponent.value.hotInstance
  const rowIndex = tableData.value.findIndex(row => row.id === targetRow.id && row.type_str === targetRow.type_str)
  
  if (rowIndex !== -1) {
    instance.scrollViewportTo(rowIndex)
    instance.selectRows(rowIndex)
  }
}

// Add function for next match
const nextMatchSearchResult = () => {
  console.log("next")
  // Reset index if out of range
  if (lastQueryIndex.value >= lastQueryResult.value.length) {
    lastQueryIndex.value = 0
    ElMessage.info('已回到第一条结果')
  }
  
  const nextSearchResult = lastQueryResult.value[lastQueryIndex.value]
  if (!nextSearchResult) {
    ElMessage.warning('没有找到匹配结果')
    return
  }
  
  const targetRow = tableData.value.find(row => 
    row.id === nextSearchResult.id && row.type_str === nextSearchResult.type_str
  )
  if (targetRow) {
    scrollToRow(targetRow)
    lastQueryIndex.value++
  } else {
    ElMessage.warning('无法找到对应内容')
  }
}

// Modify handleSearch function
const handleSearch = async () => {
  try {
    isSearching.value = true
    
    if (isSameQuery(searchQuery.value, searchType.value, selectedScriptType.value)) {
      nextMatchSearchResult()
      return
    }

    const query = buildESQuery(searchType.value, searchQuery.value, selectedScriptType.value)
    console.log('Search query:', query)
    const response = await esSearchScripts(query, 0, 9999)
    const data = response.data as ESSearchResponse<CombatScriptDocument>
    if (data?.hits?.hits) {
      const processedData = data.hits.hits.map(hit => ({
        id: hit._source.id,
        type_str: hit._source.type_str,
        desc: hit._source.desc,
        note: hit._source.note || '',
        score: hit._score
      }))
      await nextTick()
      // tableData.value = processedData
      
      // Update last query and navigate to first result
      updateLastQuery(searchQuery.value, searchType.value, selectedScriptType.value, processedData)
      nextMatchSearchResult()
      
      ElMessage.success(`找到 ${processedData.length} 条记录`)
    } else {
      tableData.value = []
      if (hotTableComponent.value?.hotInstance) {
        hotTableComponent.value.hotInstance.loadData([])
      }
      ElMessage.info('未找到匹配记录')
    }
  } catch (error) {
    console.error('Search error:', error)
    ElMessage.error('搜索失败')
  } finally {
    isSearching.value = false
  }
}

// 添加缓存相关函数
const clearCache = () => {
  console.log("clearCache")
  searchCache.value = null
  localStorage.removeItem(LOCAL_CACHE_KEY)
}

const updateCache = (data: any) => {
  searchCache.value = {
    key: Date.now().toString(),
    results: data,
    totalHits: data.length,
    timestamp: Date.now()
  }
  localStorage.setItem(LOCAL_CACHE_KEY, JSON.stringify(searchCache.value))
}

const loadLocalCache = async () => {
  const localCache = localStorage.getItem(LOCAL_CACHE_KEY)
  if (localCache == null) {
    const allSearchResult = await SearchAllCombatScript()
    updateCache(allSearchResult)
    console.log("load from remote", Date.now())
    return allSearchResult
  }
  console.log("load from local", Date.now())
  return JSON.parse(localCache).results
}

// 预处理数据 过滤无效类型并转换id，按id排序返回最后结果
const preProcessData = (data: Array<CombatScriptDocument>) => {
  // 第一步：数据清洗 - 过滤无效类型并转换id
  const cleanedData = data.reduce((acc: Array<CombatScriptDocument>, item) => {
    // 检查类型是否有效
    if (!Object.values(SCRIPT_TYPES).includes(item.type_str as any)) {
      return acc
    }
    
    // 转换id为数字类型
    const convertedId = typeof item.id === 'string' ? parseInt(item.id, 10) : item.id
    if (isNaN(convertedId)) {
      return acc
    }
    
    acc.push({
      ...item,
      id: convertedId
    })
    return acc
  }, [])
  
  // 第二步：按id排序
  const validData = cleanedData.sort((a, b) => a.id - b.id)
  return validData
}

// 优化的数据加载函数
const loadToTableShow = async (data: Array<CombatScriptDocument>) => {
  if (!hotTableComponent.value?.hotInstance) return
  
  const validData = preProcessData(data)
  
  // 更新数据
  tableData.value = validData
  await nextTick()
  // 不需要再次调用 loadData，因为 tableData 已经是响应式的了
  // hotTableComponent.value.hotInstance.loadData(validData)
  
  // 如果有类型筛选，显示提示
  if (selectedScriptType.value) {
    const filteredCount = validData.filter(item => item.type_str === selectedScriptType.value).length
    const totalCount = validData.length
    ElMessage.info(`当前显示 ${selectedScriptType.value} 类型的数据：${filteredCount}/${totalCount}`)
  } else {
    ElMessage.success(`已加载 ${validData.length} 条有效记录`)
  }
}

// 判断是否需要更新Cache
const reloadCache = async () => {
  if (searchCache.value == null && isFirstLoad.value) {
    console.log("reload Cache", Date.now());
    try {
      isSearching.value = true
      const allSearchResult = await loadLocalCache()
      console.log("load data num", allSearchResult.length)
      await loadToTableShow(allSearchResult)
      totalHits.value = allSearchResult.length
      ElMessage.success(`已加载 ${allSearchResult.length} 条记录`)
    } catch (error) {
      console.error('Load cache error:', error)
      ElMessage.error('加载缓存失败')
    } finally {
      isSearching.value = false
    }
  }
}

onBeforeMount(() => {
  console.log("beforeMounted", Date.now())
})

// 修改 onMounted
onMounted(() => {
  console.log("onMounted", Date.now())
  if (isFirstLoad.value) {
    // 只在第一次加载时执行
    window.addEventListener('load', () => {
      console.log("window load")
      clearCache()
    })
    window.addEventListener('resize', handleResize)
    nextTick(() => {
      calculateTableHeight()
    })
    reloadCache()
    isFirstLoad.value = false
  }
})

onUnmounted(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)
})

// 添加新的响应式变量
const dialogVisible = ref(false)
const isSubmitting = ref(false)
const addFormRef = ref<FormInstance>()
const addForm = ref({
  id: null as number | null,
  type_str: '',
  desc: '',
  note: ''
})

// 表单验证规则
const addFormRules = {
  id: [
    { required: true, message: '请输入脚本ID', trigger: 'blur' },
    { type: 'number', message: 'ID必须为数字', trigger: 'blur' }
  ],
  type_str: [
    { required: true, message: '请选择脚本类型', trigger: 'change' }
  ],
  desc: [
    { required: true, message: '请输入描述', trigger: 'blur' }
  ]
} as FormRules

// 添加脚本占位的响应式变量
const placeholderDialogVisible = ref(false)
const placeholderFormRef = ref<FormInstance>()
const placeholderForm = ref({
  type_str: '',
  count: 1,
  text: ''
})

// 占位表单验证规则
const placeholderFormRules = {
  type_str: [
    { required: true, message: '请选择脚本类型', trigger: 'change' }
  ],
  count: [
    { required: true, message: '请输入占位个数', trigger: 'blur' },
    { type: 'number', min: 1, max: 100, message: '个数必须在1到100之间', trigger: 'blur' }
  ],
  text: [
    { required: true, message: '请输入占位文本', trigger: 'blur' }
  ]
} as FormRules

// 显示添加对话框
const showAddDialog = () => {
  addForm.value = {
    id: null,
    type_str: '',
    desc: '',
    note: ''
  }
  dialogVisible.value = true
}

// 提交新增表单
const submitAdd = async () => {
  if (!addFormRef.value) return

  await addFormRef.value.validate(async (valid) => {
    if (valid && addForm.value.id !== null) {
      isSubmitting.value = true
      try {
        const response = await esAddScript({
          id: addForm.value.id,
          type_str: addForm.value.type_str,
          desc: addForm.value.desc,
          note: addForm.value.note || undefined
        })

        if (response.status === 201) {
          clearCache() // Clear cache after successful add
          ElMessage.success('添加成功')
          dialogVisible.value = false
          // 重新加载数据
          await loadToTableShow(tableData.value)
        } else {
          ElMessage.error('添加失败')
        }
      } catch (error: any) {
        console.error('Failed to add script:', error)
        ElMessage.error('添加失败，请稍后重试: ' + error.message)
      } finally {
        isSubmitting.value = false
      }
    }
  })
}

// 占位查询函数
const queryPlaceholder = async () => {
  searchQuery.value = SCRIPT_CONSTANTS.PLACEHOLDER_TEXT
  searchType.value = SEARCH_TYPES.CONTRAIN
  await handleSearch()
}

// 显示占位对话框
const showPlaceholderDialog = () => {
  placeholderForm.value = {
    type_str: '',
    count: 1,
    text: ''
  }
  placeholderDialogVisible.value = true
}

// 提交占位表单
const submitPlaceholder = async () => {
  if (!placeholderFormRef.value) return

  await placeholderFormRef.value.validate(async (valid) => {
    if (valid) {
      isSubmitting.value = true
      try {
        // 获取最大ID
        const maxId = await esGetMaxId(placeholderForm.value.type_str)
        console.log("maxId", maxId)
        const startId = maxId + 1

        // 批量添加脚本
        for (let i = 0; i < placeholderForm.value.count; i++) {
          await esAddScript({
            id: startId + i,
            type_str: placeholderForm.value.type_str,
            desc: `${placeholderForm.value.text}${SCRIPT_CONSTANTS.PLACEHOLDER_TEXT}`,
            note: ""
          })
        }
        clearCache()
        ElMessage.success(`成功添加${placeholderForm.value.count}个占位脚本`)
        placeholderDialogVisible.value = false

        // 执行占位查询以显示新添加的脚本
        await queryPlaceholder()
      } catch (error: unknown) {
        console.error('Failed to add placeholder scripts:', error)
        if (error instanceof Error) {
          ElMessage.error('添加占位脚本失败：' + error.message)
        } else {
          ElMessage.error('添加占位脚本失败：' + String(error))
        }
      } finally {
        isSubmitting.value = false
      }
    }
  })
}

// 监听 type_str 的变化来更新 count
watch(() => placeholderForm.value.type_str, (newType) => {
  // 根据类型更新 count 的默认值
  placeholderForm.value.count = newType === SCRIPT_TYPES.PASSIVE ? 10 : 1
})

// 添加编辑相关的响应式变量
const editDialogVisible = ref(false)
const editFormRef = ref<FormInstance>()
const editForm = ref({
  id: null as number | null,
  type_str: '',
  desc: '',
  note: ''
})

// 编辑表单验证规则
const editFormRules = {
  desc: [
    { required: true, message: '请输入描述', trigger: 'blur' }
  ]
} as FormRules

// 显示编辑对话框
const showEditDialog = (rowData: CombatScriptDocument) => {
  // 确保数据存在于 tableData 中
  const existingData = tableData.value.find(item => item.id === rowData.id && item.type_str === rowData.type_str);
  if (!existingData) {
    ElMessage.warning('无法获取行数据，请刷新页面后重试');
    return;
  }
  
  editForm.value = {
    id: existingData.id,
    type_str: existingData.type_str,
    desc: existingData.desc,
    note: existingData.note || ''
  }
  editDialogVisible.value = true
}

// 提交编辑表单
const submitEdit = async () => {
  if (!editFormRef.value) return

  await editFormRef.value.validate(async (valid) => {
    if (valid && editForm.value.id !== null) {
      isSubmitting.value = true
      try {
        const response = await esEditScript({
          id: editForm.value.id,
          type_str: editForm.value.type_str,
          desc: editForm.value.desc,
          note: editForm.value.note || '',
          score: 1  // 添加默认的 score 值
        })

        if (response.status === 200) {
          clearCache() // Clear cache after successful update
          ElMessage.success('更新成功')
          editDialogVisible.value = false
          // 重新加载数据
          await loadToTableShow(tableData.value)
        } else {
          ElMessage.error('更新失败')
        }
      } catch (error: any) {
        console.error('Failed to update script:', error)
        ElMessage.error('更新失败，请稍后重试: ' + error.message)
      } finally {
        isSubmitting.value = false
      }
    }
  })
}
</script>

<style scoped>
.table-editor-container {
  padding: 5px;
}

.table-card {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.search-row {
  margin-bottom: 20px;
}

.table-container {
  margin-top: 20px;
  position: relative;
  min-height: 500px;
  overflow: hidden;
}

:deep(.handsontable) {
  font-size: 14px;
}

:deep(.ht_master .wtHolder) {
  overflow-x: auto !important;
}

:deep(.handsontable td) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 4px 6px !important;
}

:deep(.handsontable .wtHolder) {
  overflow: hidden auto !important;
}

:deep(.handsontable .ht_clone_top) {
  z-index: 101;
}

:deep(.handsontable .ht_clone_left) {
  z-index: 102;
}

:deep(.handsontable .ht_clone_top_left_corner) {
  z-index: 103;
}

:deep(.handsontable ::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

:deep(.handsontable ::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 4px;
}

:deep(.handsontable ::-webkit-scrollbar-thumb) {
  background: #888;
  border-radius: 4px;
}

:deep(.handsontable ::-webkit-scrollbar-thumb:hover) {
  background: #555;
}

:deep(.search-result) {
  background: rgba(255, 255, 0, 0.2) !important;
}

:deep(.handsontable td.search-result) {
  background: rgba(255, 255, 0, 0.2) !important;
}
</style> 